package com.saileijieji.mymvp.view.main;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.saileijieji.mymvp.R;
import com.saileijieji.mymvp.adapter.GridImageAdapter;
import com.saileijieji.mymvp.bean.TypeSelectBean;
import com.saileijieji.mymvp.dialog.PollingzhanshiDialog;
import com.saileijieji.mymvp.mvp.base.BaseActivity;
import com.saileijieji.mymvp.tool.FullyGridLayoutManager;
import com.saileijieji.mymvp.view.TestAddressProvider;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chihane.jdaddressselector.AddressProvider;
import chihane.jdaddressselector.AddressSelector;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @describe: 巡检复查
 * @author: 武梁
 * @date: 2018/8/7 13:19
 * @mailbox: 1034905058@qq.com
 */
public class PollingUploadingActivity extends BaseActivity implements OnAddressSelectedListener {


    @Bind(R.id.upload_img_back)
    ImageView uploadImgBack;
    @Bind(R.id.upload_relay)
    RelativeLayout uploadRelay;
    @Bind(R.id.upload_edit_name)
    EditText uploadEditName;
    @Bind(R.id.upload_tv_adress)
    TextView uploadTvAdress;
    @Bind(R.id.upload_lin_adress)
    LinearLayout uploadLinAdress;
    @Bind(R.id.upload_tv_eqiupment)
    TextView uploadTvEqiupment;
    @Bind(R.id.upload_lin_equipment)
    LinearLayout uploadLinEquipment;
    @Bind(R.id.upload_tv_result)
    TextView uploadTvResult;
    @Bind(R.id.upload_lin_result)
    LinearLayout uploadLinResult;
    @Bind(R.id.upload_edit_message)
    EditText uploadEditMessage;
    @Bind(R.id.recycler)
    RecyclerView recycler;
    @Bind(R.id.upload_rela_btn)
    RelativeLayout uploadRelaBtn;
    @Bind(R.id.frameLayout)
    FrameLayout frameLayout;
    private GridImageAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int maxSelectNum = 4;
    private int themeId;
    private int chooseMode = PictureMimeType.ofImage();
    private String facilityid;
    private String facilityname;
    private List<TypeSelectBean.TypeBean> typelist;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_polling_upload);
        ButterKnife.bind(this);
        themeId = R.style.picture_default_style;
        FullyGridLayoutManager manager = new FullyGridLayoutManager(PollingUploadingActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(PollingUploadingActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        recycler.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (!selectList.isEmpty()) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            PictureSelector.create(PollingUploadingActivity.this).themeStyle(themeId).openExternalPreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(PollingUploadingActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(PollingUploadingActivity.this).externalPictureAudio(media.getPath());
                            break;
                        default:
                            break;
                    }
                }
            }
        });

        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {// Do nothing
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(PollingUploadingActivity.this);
                } else {
                    Toast.makeText(PollingUploadingActivity.this,
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {// Do nothing
            }

            @Override
            public void onComplete() {// Do nothing
            }
        });

//        AddressSelector selector = new AddressSelector(this);
//        selector.setOnAddressSelectedListener(this);
//        selector.setAddressProvider(new TestAddressProvider());
//
//        assert frameLayout != null;
//        frameLayout.addView(selector.getView());

        presenter.getData(0, this, true, apiManager.typeSelect());

    }


    @Override
    public void showData(int tag, Object data) {
        switch (tag) {
            case 0:
                TypeSelectBean bean = (TypeSelectBean) data;
                typelist = bean.getType();
                break;
            default:
        }

    }

    @OnClick({R.id.upload_img_back, R.id.upload_lin_adress, R.id.upload_lin_equipment, R.id.upload_lin_result, R.id.upload_rela_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.upload_img_back:
                onBackPressed();
                break;
            case R.id.upload_lin_adress:
                frameLayout.setVisibility(View.VISIBLE);
                BottomDialog dialog = new BottomDialog(this);
                dialog.setOnAddressSelectedListener(this);
                dialog.setAddressProvider(new TestAddressProvider());
                dialog.show();
                break;
            case R.id.upload_lin_equipment:
                PollingzhanshiDialog dialoga = new PollingzhanshiDialog(PollingUploadingActivity.this, typelist) {
                    @Override
                    public void onActionClicked(String id, String name) {
                        facilityid = id;
                        facilityname = name;
                        uploadTvEqiupment.setText(facilityname);
                    }
                };
                dialoga.show();
                break;
            case R.id.upload_lin_result:
                break;
            case R.id.upload_rela_btn:
                break;
            default:
        }
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {

            PictureSelector.create(PollingUploadingActivity.this)
                    .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .previewVideo(false)// 是否可预览视频
                    .enablePreviewAudio(false) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .withAspectRatio(3, 2)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                    .isGif(false)// 是否显示gif图片
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .openClickSound(true)// 是否开启点击声音
                    .selectionMedia(selectList)// 是否传入已选图片
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

        }

    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调
            selectList = PictureSelector.obtainMultipleResult(data);
            // 例如 LocalMedia 里面返回三种path
            // 1.media.getPath(); 为原图path
            // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
            // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
            // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
            for (LocalMedia media : selectList) {
                Log.i("图片-----》", media.getPath());
            }
            adapter.setList(selectList);
            adapter.notifyDataSetChanged();

        }
    }

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        frameLayout.setVisibility(View.GONE);
    }


}
